package com.jeect.productweb.web;

import com.jeect.base.util.ResponseBody;
import com.jeect.base.util.ResponseCode;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class AuthenticationController {

    private RequestCache requestCache = new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    @GetMapping("/auth/validate")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public ResponseBody validate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if(savedRequest!=null){
            String url = savedRequest.getRedirectUrl();
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            System.out.println("url====" + url);
            System.out.println(savedRequest);
            if(url.endsWith(".html") || url.equals(basePath)) {
                redirectStrategy.sendRedirect(request,response,"/login.html");
                return null;
            }
        }
        return new ResponseBody(ResponseCode.FAILE, "未授权...");
    }
}
